import os,json
import tornado.ioloop
import tornado.web

students = [
    {'id': 1, 'name': '张三', 'gender': '男', 'age': 18,
     'id_card': '123456789', 'phone': '12345678901', 'address': '北京'},
    {'id': 2, 'name': '李四', 'gender': '男', 'age': 19,
     'id_card': '123456780', 'phone': '12345678902', 'address': '上海'},
    {'id': 3, 'name': '王五', 'gender': '女', 'age': 20,
     'id_card': '123456781', 'phone': '12345678903', 'address': '广州'}
]

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")

class StudentsHandler(tornado.web.RequestHandler):
    
    def get(self):
        self.write(json.dumps(students))
    
    # 添加学生信息
    def post(self):
        args = tornado.escape.json_decode(self.request.body)
        new_student = {
            'id': int(args['id']),
            'name': args['name'],
            'gender': args['gender'],
            'age': args['age'],
            'id_card': args['id_card'],
            'phone': args['phone'],
            'address': args['address']
        }
        students.append(new_student)
        self.write(json.dumps(new_student))

class StudentHandler(tornado.web.RequestHandler):
    # 获取单个学生信息
    def get(self,id):
        for student in students:
            if student['id'] == int(id):
                return self.write(json.dumps(student))
        return self.write({'error': 'Student not found'})
    
    # 修改学生信息
    def put(self,id):
        args = tornado.escape.json_decode(self.request.body)
        for student in students:
            if student['id'] == int(id):
                student['name'] = args['name']
                student['gender'] = args['gender']
                student['age'] = args['age']
                student['id_card'] = args['id_card']
                student['phone'] = args['phone']
                student['address'] = args['address']
                return self.write(json.dumps(student))
        return self.write({'error': 'Student not found'})
    
    # 删除学生信息
    def delete(self,id):
        for student in students:
            if student['id'] == int(id):
                students.remove(student)
            return self.write(json.dumps({'result': True}))
        return self.write({'error': 'Student not found'})


class Application(tornado.web.Application):                          
    def __init__(self):        
        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),     
        )
                                                           
        handlers = [
            (r'/', MainHandler),     
            (r'/students', StudentsHandler),    
            (r'/students/(\d+)', StudentHandler), 
        ]

        tornado.web.Application.__init__(self, handlers, **settings)

if __name__ == "__main__":
    app = Application()
    app.listen(80)
    tornado.ioloop.IOLoop.current().start()
